package com.ssy.lingxi.message.serviceimpl;

import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.message.entity.PushDevice;
import com.ssy.lingxi.message.jpush.AliasUtil;
import com.ssy.lingxi.message.jpush.JPushService;
import com.ssy.lingxi.message.model.vo.PushDeviceAddRequest;
import com.ssy.lingxi.message.repository.PushDeviceRepository;
import com.ssy.lingxi.message.service.IMobilePushMessageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.ssy.lingxi.message.jpush.AliasUtil.getAlias;

/**
 * App推送消息服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2020/10/27
 */
@Service
public class MobilePushMessageServiceImpl implements IMobilePushMessageService {

    @Resource
    private PushDeviceRepository pushDeviceRepository;
    @Resource
    private JPushService jPushService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> addPushDevice(PushDeviceAddRequest request) {
        // 一个别名只能绑定10台设备, 即memberId-roleId, 只能关联10个registrationId
        // 查询别名已经绑定的设备
        List<PushDevice> pushDeviceList = pushDeviceRepository.findAllByMemberIdAndRoleIdAndUserId(request.getMemberId(), request.getRoleId(), request.getUserId());
        if (pushDeviceList.size() >= jPushService.getMaxAliasBindDevice()) {
            // 获取创建时间最早的记录并删除
            Optional<PushDevice> pushDeviceOptional = pushDeviceList.stream().min(Comparator.comparing(PushDevice::getCreateTime));
            pushDeviceOptional.ifPresent(pushDevice -> {
                pushDeviceRepository.deleteById(pushDevice.getId());
                jPushService.deleteByRegistrationId(AliasUtil.getAlias(request.getMemberId(), request.getRoleId(), request.getUserId()), request.getRegistrationId());
            });
        }

        // 查询设备绑定的别名信息
        PushDevice pushDevice = pushDeviceRepository.findByRegistrationId(request.getRegistrationId());
        if (Objects.isNull(pushDevice)) {
            pushDevice = new PushDevice();
            pushDevice.setMemberId(request.getMemberId());
            pushDevice.setRoleId(request.getRoleId());
            pushDevice.setUserId(request.getUserId());
            pushDevice.setRegistrationId(request.getRegistrationId());
            pushDevice.setCreateTime(System.currentTimeMillis());
            pushDeviceRepository.saveAndFlush(pushDevice);

            // 设置别名
            jPushService.setAlias(getAlias(request.getMemberId(), request.getRoleId(), request.getUserId()), request.getRegistrationId());
        } else {
            boolean aliasFlag = pushDevice.getMemberId().equals(request.getMemberId())
                    && pushDevice.getRoleId().equals(request.getRoleId());
            // 判断别名信息是否一样
            if (aliasFlag) {
                return Wrapper.success();
            }

            // 不一样则更新
            pushDevice.setMemberId(request.getMemberId());
            pushDevice.setRoleId(request.getRoleId());
            pushDevice.setUserId(request.getUserId());
            pushDeviceRepository.saveAndFlush(pushDevice);

            // 设置别名
            jPushService.setAlias(AliasUtil.getAlias(request.getMemberId(), request.getRoleId(), request.getUserId()), request.getRegistrationId());
        }

        return Wrapper.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Wrapper<Void> deletePushDevice(PushDeviceAddRequest request) {
        PushDevice pushDevice = pushDeviceRepository.findByRegistrationId(request.getRegistrationId());
        if (Objects.nonNull(pushDevice)) {
            pushDeviceRepository.deleteById(pushDevice.getId());
        }

        jPushService.deleteByRegistrationId(AliasUtil.getAlias(request.getMemberId(), request.getRoleId(), request.getUserId()), request.getRegistrationId());

        return Wrapper.success();
    }

}